package keter.framework.web.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/* @WebFilter对 /authenticate post请求不生效的原因猜测:
 * 由于"/authenticate"已被spring的filter拦截处理过，因此通过注解配置的拦截器不生效
 */
public class CaptchaFilter implements Filter {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(CaptchaFilter.class);

    private static boolean enabled;

    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        enabled = Boolean.valueOf(filterConfig.getInitParameter("enabled"));
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
//    	HttpServletRequest request = (HttpServletRequest) req;
//        logger.info("~~~~~  captcha context:{} ~~~~~~~~~~",request.getRequestURI());
        // 判断是否启用验证码功能
        if (!enabled) {
            chain.doFilter(req, res);
            return;
        }
        checkCode(req, res, chain);
    }

    /**
     * <p>
     * Method ：checkKaptcha
     * <p>
     * Description : 核对验证码
     *
     * @param req
     * @param res
     * @param chain
     * @throws IOException
     * @throws ServletException
     * @author 顾力行-gulixing@msn.com
     */
    private void checkCode(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String guess = request.getParameter("captchaGuess");
        if(CaptchaCache.checkCode(request,guess)==true){
            chain.doFilter(request, response);
        }
        else{
            logger.info("验证码错误!");
        	response.sendRedirect(getServletContext().getContextPath() + "/login?error=2");
        }
    }

    protected final ServletContext getServletContext() {
        return this.filterConfig.getServletContext();
    }

    @Override
    public void destroy() {
    }

}
